<template>
  <view class="page">
    <!-- #ifdef H5 -->
    <custom-navbar title="搜索机型" />
    <!-- #endif -->
    <custom-nav
      :searchVal.sync="searchKey"
      @onInput="onInput"
    />
    <view class="main">
    
      <search-product-list
        v-if="searchKey"
        :products="products"
        :searchKey="searchKey"
        :loading="loading"
        @onClick="handleProductClick"
      />

      <hot-search
        v-else
        :hotList="hotSearchList"
        @onClick="handleProductClick"
        @onCategory="handleCategoryClick"
        @onBrand="handleBrandClick"
      />
    </view>
  </view>
</template>


<script>
import _ from 'lodash'
import { fetchHotList, fetchProductSearch } from '@/api'

import customNav from './components/customNav.vue'
import HotSearch from './components/hotSearch.vue'
import searchProductList from './components/searchProductList.vue'


export default {
  name: "Search",
  components: { customNav, HotSearch, searchProductList },
  data() {
    return {

      searchKey: '',

      hotSearchList: [],

      loading: false,
      products: [],
    }
  },


  onLoad(options) {
    this.loadHotList()
  },

  methods: {
    loadHotList() {
      fetchHotList({ categoryId: 100001, size: 10 }).then(({ code, data }) => {
        if (code === 200) {
          this.hotSearchList = data || []
        }
      })
    },

    async loadList() {
      try {
        this.loading = true
        this.products = []
        const {data,code} = await fetchProductSearch({
          keywords: this.searchKey,
        });
          console.log("==================>",data)
          if (code === 200) {
            this.products = data || []
        }
        
      }catch(e){
          console.log(e)
        } finally {
        setTimeout(() => {
          this.loading = false
        }, 100);
      }
    },

    onInput: _.debounce(function() {
      if (!this.searchKey) { return }
      this.loadList()
    }, 500),

    handleProductClick(item) {
      this.goPage('product', { id: item.productId })
    },
  }
}
</script>


<style lang="scss" scoped>
.page{
  padding-top: 112rpx;
  background-color: #fff;
  min-height: 100vh;
  /* #ifdef H5 */
  padding-top: calc(var(--status-bar-height) + 88rpx);
  /* #endif */
}
</style>